<?php

namespace Controller\Admin;

use Daiyong\Db as db;

class Common extends \Controller\Common {
    public $loginUser = [];
    public function __construct() {
        parent::__construct();
        //连接数据库
        db::connect($this->config['db']);
        //进行用户验证
        $this->loginUser = $this->getLoginInfo();
        if ($this->loginUser === false) $this->echo(99, '未登录');
        $this->checkPower();
    }
    //不需要权限可直接访问的页面
    private function noAuth() {
        if (
            CONTROLLER == 'auth' || //Auth.php无需验证权限也可访问
            $this->loginUser['id'] == 1 || //管理员id为1无需验证权限
            //修改个人信息时传图片无需验证权限
            ($this->loginUser['id'] && strpos($_SERVER['REQUEST_URI'], '/uploads/image') && strpos($_SERVER['HTTP_REFERER'], '/admin/edit?id=my'))
        ) {
            return true;
        }
        return false;
    }
    //检查权限
    private function checkPower() {
        if ($this->loginUser) {
            //判断权限
            if (!$this->noAuth()) {
                $power = CONTROLLER . '/' . ACTION;
                if (!in_array($power, $this->loginUser['group']['power'])) {
                    $this->echo(98, '暂无权限:' . $power);
                }
            }
        }
    }
    //判断登陆
    private function getLoginInfo() {
        //获取token
        $authorization = $_SERVER['HTTP_AUTHORIZATION'];
        if (!$authorization) $authorization = $_GET['authorization'];
        //查询用户
        if ($authorization && strlen($authorization) == 32) {
            $adminModel = new \Model\Admin();
            $user = $adminModel->find(['token' => $authorization]);
            if ($user['id']) return $user;
        }
        if ($this->noAuth()) { //不需要权限可直接访问的页面
            return [];
        } else {
            return false;
        }
    }
}
